// import { to, rto } from '@/utils/js/navigate.js'
const app =  getApp();

/**
 * 两位补零
 */
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 手机中间四位隐藏
function mobileSubstring(str){
  if(str!=undefined)
  return str.substring(0,3) + '****' + str.substring(7,11)
};

/**
 * 函数防抖
 */
function debounce(fn, delay) {
  // 维护一个 timer，用来记录当前执行函数状态
  let timer = null;

  return function () {
    // 通过 ‘this’ 和 ‘arguments’ 获取函数的作用域和变量
    let context = this;
    let args = arguments;
    // 清理掉正在执行的函数，并重新执行
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  }
}

// 1秒内避免重复点击
function repeatBtn(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1000
  }

  let _lastTime = null

  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}

// 手机号加密
function formEncrypt(val,front,after) {
	return val.substring(0,front)+'*'.repeat(val.length-(front+after))+val.substring(val.length-after);
}


// 判断是否为IPhonX系列
function getSystemInfoForPhone() {
  let isIpx = false,
    systemInfo = uni.getSystemInfoSync(),
    model = uni.getSystemInfoSync().model;
		
  //x及以上的异形屏top为44，非异形屏为20
  if (systemInfo.safeArea.top > 20 || model.search('iPhone X') != -1) { 
    isIpx = true;
  }
  return isIpx;
}

// 判断是否为IPhon5系列
function getSystemInfoForPhoneFive() {
  let isIphoneFive = false,
    model = uni.getSystemInfoSync().model;
  // 获取手机号机型
  if (model.search('iPhone 5') != -1 || model.search('iPhone 5s') != -1 || model.search('iPhone SE') != -1) {
    isIphoneFive = true;
  }
  return isIphoneFive;
}

// 判断是否为华为荣耀V10系列
function getSystemInfoForHWV10() {
  let isHWV10 = false,
    systemInfo = uni.getSystemInfoSync(),
    model = uni.getSystemInfoSync().model;
  
  // 获取手机号机型
  if (model.search('BKL-AL00') != -1 && info.brand == "HONOR") {
    isHWV10 = true;
  }
  return isHWV10;
}

// 在此函数中获取扫描普通链接二维码参数
let getQueryString = function (url,name) {
  var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  var r = url.substr(1).match(reg)
  if (r != null) {
   return r[2]
  }
  return null;
 }


/**
 *
 * @description 数组-排序
 */
function sortBy(sortKey,rev){
  if( rev == undefined){
    rev = 1;
  }
  else{
    rev = (rev) ? 1 : -1;
  }
  return function(a , b){
    a = a[sortKey];
    b = b[sortKey];

    if( a < b) //返回小于零的值，数组将按照升序排列。
    {
      return rev * -1;
    }
    if( a > b ) //返回大于零的值，数组将按照降序排列。
    {
      return rev * 1;
    }
    return 0;
  }
}

/**
 * 需要登录的页面跳转用此进行判断跳转到登录页
 * @param url
 * @returns {boolean}
 */
function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

/**
 * 统一错误model提示
 * @param msg
 */
function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/images/icon/icon_error.png'
  })
}

// 计算时间为刚刚、几分钟前、几小时前、几天前
function timeago(dateTimeStamp, opType){
	let minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
	let hour = minute * 60;
	let day = hour * 24;
	let week = day * 7;
	let halfamonth = day * 15;
	let month = day * 30;
	let now = new Date().getTime();   //获取当前时间毫秒
	let diffValue = now - dateTimeStamp;//时间差
	let result;

	if(diffValue < 0){
		return;
	}
	let minC = diffValue/minute;  //计算时间差的分，时，天，周，月
	let hourC = diffValue/hour;
	let dayC = diffValue/day;
	let weekC = diffValue/week;
	let monthC = diffValue/month;
	//此处考虑小数情况
	// if(monthC >= 1 && monthC < 4){
	// 	result = " " + parseInt(monthC) + "月前"
	// }else if(weekC >= 1 && weekC < 4){
	// 	result = " " + parseInt(weekC) + "周前"
	// }else 
	if(dayC >= 1 && dayC < 7){
		result = " " + parseInt(dayC) + "天前"
	}else if(hourC >= 1 && hourC < 24){
		result = " " + parseInt(hourC) + "小时前"
	}else if(minC >= 1 && minC < 60){
		result =" " + parseInt(minC) + "分钟前"
	}else if(diffValue >= 0 && diffValue <= minute){
		result = "刚刚"
	}else {
		let datetime = new Date();
		datetime.setTime(dateTimeStamp);
		let Nyear = datetime.getFullYear();
		let Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		let Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		let Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		let Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		let Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		if(opType == 1) result = Nmonth + "-" + Ndate + ' ' + Nhour + ':' + Nminute + ':' + Nsecond;
		else result = Nyear + "-" + Nmonth + "-" + Ndate;
	}
	return result;
}

// 根据证件类型id显示证件名称
function userInfoIdType(idType) {
	let idTypeName = '';
	switch (idType) {
		case 1:
			idTypeName = '身份证'
			break;
		case 2:
			idTypeName = '护照'
			break;
		case 3:
			idTypeName = '军官证'
			break;
		case 4:
			idTypeName = '台胞证'
			break;
		case 5:
			idTypeName = '回乡证'
			break;
		case 6:
			idTypeName = '出生证明'
			break;
		case 7:
			idTypeName = '户口本'
			break;
		case 8:
			idTypeName = '外国人永久居留证'
			break;
		case 9:
			idTypeName = '港澳台居民居住证'
			break;
		case 10:
			idTypeName = '其他证件'
			break;
		case 11:
			idTypeName = '台湾通行证'
			break;
		case 12:
			idTypeName = '港澳通行证'
			break;
	}
	return idTypeName;
}

// 将秒转化为时分秒
function formatSeconds(value) {
    let result = parseInt(value)
    let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
    let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
    let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
 
    let res = '';
    if(h !== '00') res += `${h}:`;
		else res += `00:`;
    if(m !== '00') res += `${m}:`;
		else res += `00:`;
    res += `${s}`;
    return res;
}

// h5调起app方法
function tapOpenApp() {
	let u = navigator.userAgent;
	// var isWeixin = u.toLowerCase().indexOf('micromessenger') !== -1; // 微信内
	// if (!isWeixin) {
	// 	uni.showToast({ title: '请在微信中打开', icon: 'none', duration: 2000 });
	// 	return false;
	// }
	const platform = uni.getSystemInfoSync().platform;
	if (platform == 'ios')  this.tapOpenIOSApp();
	else if (platform == 'android') this.tapOpenAndroidApp();
	// if (platform == 'ios') window.location.href = "https://appdown.n9c.cn/apps/4/plats/5";
	// else if (platform == 'android') window.location.href = "https://appdown.n9c.cn/apps/4/plats/6";
}
// h5调起app方法-ios
function tapOpenIOSApp() {
	uni.showLoading({ title: '加载中...' });
	const currentTime = +(new Date());
	window.location.href = "https://app.yybd.vip"; // UrlSchemes
	// window.location.href = "yybd_start_app"; // UrlSchemes
	//启动间隔20ms运行的定时器，并检测累计消耗时间是否超过3000ms，超过则结束
	let _count = 0,
		timer;
	timer = setInterval(function() {
		_count++;
		const endTime = +(new Date()) - currentTime;
		if (_count >= 100 || endTime > 3000) {
			uni.hideLoading()
			clearInterval(timer);
			let hidden = window.document.hidden || window.document.mozHidden || window.document
				.msHidden || window.document.webkitHidden;
			if (typeof hidden == "undefined" || hidden == false) {
				//App store下载地址
				window.location.href = "https://app.yybd.vip"; //下载地址 可以直接跳转到appstore的
			}
		}
	}, 20);
}
// h5调起app方法-android
function tapOpenAndroidApp() {
	uni.showLoading({ title: '加载中...' });
	const currentTime = new Date().getTime();
	window.location.href = "yybd_start_app://yybd"; // UrlSchemes
	// window.location.href = "yybd_start_app"; // UrlSchemes
	// 启动间隔20ms运行的定时器，并检测累计消耗时间是否超过2000ms,超时则结束
	let _count = 0,
		timer;
	timer = setInterval(() => {
		_count++;
		const endTime = new Date().getTime() - currentTime;
		if (_count >= 200 || endTime > 5000) {
			uni.hideLoading()
			clearInterval(timer);
			let hidden = window.document.hidden || window.document.mozHidden || window.document
				.msHidden || window.document.webkitHidden;
			if (typeof hidden == "undefined" || hidden == false) {
				window.location.href = "https://app.yybd.vip"; //下载地址
			}
		}
	}, 20)
}
// h5调起app方法---提示
function tapOpenAppTip() {
	return '可能离开微信，打开第三方应用';
	// return '如果你已下载App，请到App中操作。接下来会跳转到下载页面，是否继续？';
}

// 调用app方法(webview_flutter)，通知app跳转到下一个页面。appobject是app那边定义的方法
function jumpToApp(obj){
  // h5直接跳转
  // to(obj.url, obj.objoptions);
	
  // 调用app方法
  // let http = 'http://192.168.1.34:8080'; // 本地
  // let http = 'http://192.168.8.121:8080'; // 本地
  // let http = 'http://192.168.1.211:8080'; // lily本地
  let http = 'https://yyb.ccmapp.cn'; // 线上
  // let http = 'https://testyyb.ccmapp.cn'; // 线下
  if(obj.url) obj.url = http + obj.url; // 地址前面加上域名
  appobject.postMessage(JSON.stringify(obj));
}
		

module.exports = {
  debounce,
	mobileSubstring,
  repeatBtn,
  getSystemInfoForPhone,
  getSystemInfoForPhoneFive,
  getSystemInfoForHWV10,
  sortBy,
  getQueryString,
  redirect,
  showErrorToast,
	timeago,
	formEncrypt,
	formatSeconds,
	userInfoIdType,
  jumpToApp,
	tapOpenApp,
	tapOpenIOSApp,
	tapOpenAndroidApp,
	tapOpenAppTip,
}
